﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Happy.Event.Internal
{
    internal sealed class EventInterceptorChain
    {
        private IEventPublishContext _eventPublishContext;
        private EventInterceptorAttribute[] _eventInterceptors;
        private Action _subscribersExecutor;
        private int _currentEventInterceptorIndex = -1;

        internal EventInterceptorChain(
            IEventPublishContext eventPublishContext,
            EventInterceptorAttribute[] eventInterceptors,
            Action subscribersExecutor)
        {
            _eventPublishContext = eventPublishContext;
            _eventInterceptors = eventInterceptors.OrderBy(x => x.Order).ToArray();
            _subscribersExecutor = subscribersExecutor;
        }

        private EventInterceptorAttribute CurrentEventInterceptor
        {
            get
            {
                return _eventInterceptors[_currentEventInterceptorIndex];
            }
        }

        internal void ExecuteNext()
        {
            _currentEventInterceptorIndex++;

            if (_currentEventInterceptorIndex < _eventInterceptors.Length)
            {
                this.CurrentEventInterceptor.Intercept(_eventPublishContext);
            }
            else
            {
                _subscribersExecutor();
            }
        }
    }
}
